const bcrypt = require('bcryptjs');
const { v4: uuidv4 } = require('uuid');

// 模拟用户集合
let users = [];

// 默认管理员用户
const createDefaultAdmin = async () => {
  if (users.length === 0) {
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash('admin123', salt);
    
    users.push({
      _id: uuidv4(),
      username: 'admin',
      password: hashedPassword,
      email: 'admin@example.com',
      role: 'admin',
      permissions: {
        system: true,
        file: true,
        nginx: true,
        database: true,
        security: true,
        task: true,
        app: true
      },
      lastLogin: null,
      active: true,
      createdAt: new Date()
    });
  }
};

// 初始化默认用户
createDefaultAdmin();

// 模拟用户模型
class MockUser {
  constructor(userData) {
    this._id = uuidv4();
    this.username = userData.username;
    this.password = userData.password;
    this.email = userData.email;
    this.role = userData.role || 'user';
    this.permissions = userData.permissions || {
      system: false,
      file: false,
      nginx: false,
      database: false,
      security: false,
      task: false,
      app: false
    };
    this.lastLogin = userData.lastLogin || null;
    this.active = userData.active !== undefined ? userData.active : true;
    this.createdAt = new Date();
  }

  // 保存用户
  async save() {
    // 处理更新现有用户的情况
    const existingIndex = users.findIndex(user => user._id === this._id);
    
    if (existingIndex !== -1) {
      // 如果是管理员角色，自动赋予所有权限
      if (this.role === 'admin') {
        this.permissions = {
          system: true,
          file: true,
          nginx: true,
          database: true,
          security: true,
          task: true,
          app: true
        };
      }
      
      users[existingIndex] = { ...this };
      return this;
    }
    
    // 处理新用户的密码哈希
    if (!this.password.startsWith('$2a$')) {
      const salt = await bcrypt.genSalt(10);
      this.password = await bcrypt.hash(this.password, salt);
    }
    
    // 如果是管理员角色，自动赋予所有权限
    if (this.role === 'admin') {
      this.permissions = {
        system: true,
        file: true,
        nginx: true,
        database: true,
        security: true,
        task: true,
        app: true
      };
    }
    
    users.push(this);
    return this;
  }

  // 验证密码
  async comparePassword(password) {
    return await bcrypt.compare(password, this.password);
  }

  // 模拟静态方法
  static async findOne(filter) {
    if (filter.username) {
      return users.find(user => user.username === filter.username) || null;
    }
    if (filter.email) {
      return users.find(user => user.email === filter.email) || null;
    }
    return null;
  }

  static async findById(id) {
    return users.find(user => user._id === id) || null;
  }

  static async countDocuments() {
    return users.length;
  }

  static async find() {
    return [...users];
  }

  // 提供选择字段功能的方法
  static select(fields) {
    return {
      async find() {
        if (fields === '-password') {
          return users.map(user => {
            const { password, ...rest } = user;
            return rest;
          });
        }
        return [...users];
      },
      async findById(id) {
        const user = users.find(user => user._id === id);
        if (!user) return null;
        
        if (fields === '-password') {
          const { password, ...rest } = user;
          return rest;
        }
        return user;
      }
    };
  }
}

module.exports = MockUser; 